//
//  ZMHomeCollectionViewController.m
//  DaMei
//
//  Created by mac on 16/2/21.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ZMHomeCollectionViewController.h"
#import "ZMNavTopView.h"
#import "ZMCategoryViewController.h"
#import "ZMdistrictViewController.h"
#import "ZMCitysModel.h"
#import "ZMSortViewController.h"
#import "ZMCategoryModel.h"
#import "ZMDistrictModel.h"
#import "ZMSortModel.h"
#import "ZMDealCell.h"
#import "ZMDealModel.h"


@interface ZMHomeCollectionViewController ()<DPRequestDelegate,AwesomeMenuDelegate>

/** 顶部的分类Item*/
@property (nonatomic, strong) UIBarButtonItem *categoryItem;
/** 顶部的区域Item*/
@property (nonatomic,strong) UIBarButtonItem *districtItem;
/** 顶部的排序Item*/
@property (nonatomic, strong) UIBarButtonItem *sortItem;

/** 选中的城市名*/
@property (nonatomic, copy) NSString *selectCityName;
/** 选中的分类名*/
@property (nonatomic, copy) NSString *selectCategoryName;
/** 选中的区域名*/
@property (nonatomic, copy) NSString *selectDistrictName;
/** 选中的排序值*/
@property (nonatomic, strong) NSNumber *selectSortValue;
/** 团购模型数据*/
@property (nonatomic, strong) NSMutableArray *dealsArray;
/** 当前请求页数*/
@property (nonatomic) NSInteger currentPageIndex;

/** 最后一次请求*/
@property (nonatomic, strong) DPRequest *lastRequest;

/** 团购页面总数*/
@property (nonatomic) NSInteger totalCount;

/** 无数据时显示图片*/
@property (nonatomic, strong) UIImageView *noDataImage;


@end

@implementation ZMHomeCollectionViewController

static NSString * const reuseIdentifier = @"dealCell";

#pragma mark 重写init方法, 设置layout
- (instancetype)init
{
    self = [super init];
    if (self) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(305, 305);
        
        self = [self initWithCollectionViewLayout:flowLayout];
        
        
    }
    return self;
}

#pragma mark 懒加载无数据时显示图片noDataImage
- (UIImageView *)noDataImage {
    
    if (!_noDataImage) {
        _noDataImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_deals_empty"]];
        
        [self.collectionView addSubview:_noDataImage];
        [_noDataImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.equalTo(self.collectionView);
        }];
    }
    return _noDataImage;
}

///屏幕发生旋转时，用于屏幕适配
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {

//    判断列数
    NSInteger col = size.width == 1024 ? 3 : 2 ;
    
//    获取当前布局
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionViewLayout;
    
//    计算间距
    CGFloat inset = (size.width - flowLayout.itemSize.width * col)/(col + 1);
    
//    flowLayout.minimumInteritemSpacing = inset;
    flowLayout.sectionInset = UIEdgeInsetsMake(inset, inset, inset, inset);
    flowLayout.minimumLineSpacing = inset;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    初始化可辨数组
    self.dealsArray = [NSMutableArray array];
    
//    调用屏幕适配方法
    [self viewWillTransitionToSize:[UIScreen mainScreen].bounds.size withTransitionCoordinator:self.transitionCoordinator];
//    设置背景颜色
    self.collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Register cell classes
//    [self.collectionView registerClass:[ZMDealCell class] forCellWithReuseIdentifier:reuseIdentifier];
    
    ///注册cell，从xib加载要用以下方法
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZMDealCell"  bundle:nil]forCellWithReuseIdentifier:reuseIdentifier];
    
    // Do any additional setup after loading the view.
    //设置左边导航栏
    [self setupLeftNav];
    
    //设置右边导航栏
    [self setupRightNav];
    
    //添加城市选中通知
    [ZMNotificationCenter addObserver:self selector:@selector(cityDidChangeNotifacation:) name:ZMCityDidChangeNotifacation object:nil];
    
    //添加选中区域的通知
    [ZMNotificationCenter addObserver:self selector:@selector(districtDidChangeNotifacation:) name:ZMDistrictDidChangeNotifacation object:nil];
    
    //添加分类选中的通知
    [ZMNotificationCenter addObserver:self selector:@selector(categoryDidChangeNotifacation:) name:ZMCategoryDidChangeNotifacation object:nil];
    
    //添加排序选中的通知
    [ZMNotificationCenter addObserver:self selector:@selector(sortDidChangeNotifacation:) name:ZMSortDidChangeNotifacation object:nil];
    //添加AwesomeMenu按钮
    [self setupAwesomeMenu];
    
    //添加刷新功能
    [self addRefresh];
    
    //页面加载时就刷新
    [self.collectionView.header beginRefreshing];
}
#pragma mark - 添加刷新功能
- (void) addRefresh {
    //下拉刷新
    __weak typeof(self) weakSelf = self;
    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf loadNewDeals];
    }];
    //添加上拉更多
    [self.collectionView addLegendFooterWithRefreshingBlock:^{
        [weakSelf loadMoreDeals];
    }];
}
#pragma mark - 添加AwesomeMenu
- (void) setupAwesomeMenu {
    
    //1. 中间的startItem
    AwesomeMenuItem *menuItem = [[AwesomeMenuItem alloc]
                                  initWithImage:[UIImage imageNamed:@"icon_pathMenu_background_normal"]
                                  highlightedImage:[UIImage imageNamed:@"icon_pathMenu_background_highlighted"]
                                  ContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_normal"]
                                  highlightedContentImage:nil];
    
    //2. 添加其他几个按钮
    AwesomeMenuItem *menuItem0 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_highlighted"]];
    
    AwesomeMenuItem *menuItem1 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_highlighted"]];
    
    AwesomeMenuItem *menuItem2 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_scan_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_scan_highlighted"]];
    
    AwesomeMenuItem *menuItem3 = [[AwesomeMenuItem alloc]
                              initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"]
                              highlightedImage:nil
                              ContentImage:[UIImage imageNamed:@"icon_pathMenu_more_normal"]
                              highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_more_highlighted"]];
    
    AwesomeMenu *menu = [[AwesomeMenu alloc] initWithFrame:CGRectZero startItem:menuItem menuItems:@[menuItem0,menuItem1,menuItem2,menuItem3]];
    
    [self.view addSubview:menu];
    
    //4. 设置按钮属性
    //4.1 停止转动
    menu.rotateAddButton = NO;
    
    //4.2 周边按钮弹出的角度 90
    menu.menuWholeAngle = M_PI_2;
    
    //4.3 按钮的位置 --> 改位置的时候必须设置一下startPoint
    menu.startPoint = CGPointMake(100, -100);
    
    [menu mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.bottom.equalTo(self.collectionView);
//        make.left.equalTo(self.collectionView).offset = 100;
//        make.bottom.equalTo(self.collectionView).offset = -100;
    }];
    
    //5. 设置代理
    menu.delegate = self;
    
    //6. 设置透明度
    menu.alpha = 0.7;
}

#pragma mark 按钮选中索引方法
- (void)awesomeMenu:(AwesomeMenu *)menu didSelectIndex:(NSInteger)idx
{
    //1. 换图片
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_mainMine_normal"];
    
    //2. 透明度
    menu.alpha = 0.7;
    
    switch (idx) {
        case 0:
            NSLog(@"0");
            break;
        case 1:
            NSLog(@"1");
            break;
        case 2:
            NSLog(@"2");
            break;
        case 3:
            NSLog(@"3");
            break;
            
        default:
            break;
    }
}
#pragma mark 按钮打开方法
- (void)awesomeMenuDidFinishAnimationOpen:(AwesomeMenu *)menu
{
    //1. 换图片
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_cross_normal"];
    
    //2. 透明度
    menu.alpha = 1;
}
#pragma mark 按钮关闭方法
- (void)awesomeMenuDidFinishAnimationClose:(AwesomeMenu *)menu
{
    //1. 换图片
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_mainMine_normal"];
    
    //2. 透明度
    menu.alpha = 0.7;
}


#pragma mark - 通知方法

#pragma mark 城市选中通知
- (void)cityDidChangeNotifacation:(NSNotification *)notification {

    self.selectCityName = notification.userInfo[ZMSelectCityName];
    
    ZMNavTopView *navTopView = self.districtItem.customView;
    [navTopView setTitle:[NSString stringWithFormat:@"%@-全部",self.selectCityName]];
    [navTopView setSubTitle:@""];
    
    [self loadNewDeals];
}

#pragma mark 区域选中通知
- (void)districtDidChangeNotifacation:(NSNotification *)notification {
    
    //1. 获取通知的值
     ZMDistrictModel *districtModel = notification.userInfo[ZMSelectDistrictModel];
    NSString *selectDistrictSubName = notification.userInfo[ZMSelectDistrictSubtitle];
    
    //2. 设置导航栏View
    ZMNavTopView *navTopView = self.districtItem.customView;
    [navTopView setTitle:[NSString stringWithFormat:@"%@-%@", self.selectCityName,districtModel.name ]];
    [navTopView setSubTitle:selectDistrictSubName];
    
    //3. 取消控制器的显示
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (districtModel.subdistricts.count == 0 || [selectDistrictSubName isEqualToString:@"全部"]) {
        self.selectDistrictName = districtModel.name;
        
    } else {
        self.selectDistrictName = selectDistrictSubName;
    }
    
    if ([self.selectDistrictName isEqualToString:@"全部"]) {
        self.selectDistrictName = nil;
    }
    
    [self loadNewDeals];
}

#pragma mark 分类选中通知
- (void)categoryDidChangeNotifacation:(NSNotification *)notification {

    //1. 获取通知的值
    ZMCategoryModel *categoryModel = notification.userInfo[ZMSelectCategoryModel];
    NSString *selectCategorySubName = notification.userInfo[ZMSelectCategorySubtitle];
    
    //2. 设置导航栏View
    ZMNavTopView *navTopView = self.categoryItem.customView;
    [navTopView setTitle:categoryModel.name];
    [navTopView setSubTitle:selectCategorySubName];
    [navTopView setIconWithName:categoryModel.small_icon withHighlightIconName:categoryModel.highlighted_icon];
    
    
    if (categoryModel.subcategories == 0 || [selectCategorySubName isEqualToString:@"全部"]) {
        self.selectCategoryName = categoryModel.name;
        
    } else {
        self.selectCategoryName = selectCategorySubName;
    }
    
    if ([self.selectCategoryName isEqualToString:@"全部分类"]) {
        self.selectCategoryName = nil;
    }
    
    
    //3. 取消控制器的显示
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [self loadNewDeals];
}

#pragma mark 排序选中通知
- (void)sortDidChangeNotifacation:(NSNotification *)notification {
    
    //1. 获取通知的值
    ZMSortModel *sortModel = notification.userInfo[ZMSelectSortModel];
    
    //NSLog(@"sortModel:%@", sortModel.label);
    
    //2. 设置导航栏View
    ZMNavTopView *navTopView = self.sortItem.customView;
    [navTopView setSubTitle:sortModel.label];
    
    self.selectSortValue = sortModel.value;
    
    //3. 取消控制器的显示
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [self loadNewDeals];
}

#pragma mark 移除通知
- (void)dealloc {

    [ZMNotificationCenter removeObserver:self];
}


#pragma mark - 网络请求
- (void) loadDeals {
    //    1.创建DPAPI类
    DPAPI *api = [DPAPI new];
    
    //    2.拼接请求数据参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"city"] = self.selectCityName == nil ? @"北京" : _selectCityName;
    
    if (self.selectCategoryName) {
        params[@"category"] = self.selectCategoryName;
    }
    if (self.selectDistrictName) {
        params[@"region"] = self.selectDistrictName;
    }
    if (self.selectSortValue) {
        params[@"sort"] = self.selectSortValue;
    }
    
    params[@"page"] = @(self.currentPageIndex);
    
    //    3.发送通知
    self.lastRequest = [api requestWithURL:@"v1/deal/find_deals" params:params delegate:self];
}

#pragma mark - 下拉刷新
///加载新的团购数据
- (void)loadNewDeals {
    
    //保证当前页面为1
    self.currentPageIndex = 1;
    
    //加载数据
    [self loadDeals];
    
}
#pragma mark - 上拉更多
- (void) loadMoreDeals {
    
    //保证页码自增
    self.currentPageIndex++;
    
    [self loadDeals];
}


#pragma mark 请求成功后获取数据的代理方法

- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result {
    
//    判断当前请求结果是否为最后一次请求，若不是，则不对数据进行保存，避免数据重复请求
    if (request != self.lastRequest) {
        return;
    }
    
//    判断是否为下拉刷新，是，则清空数组所有数据，重新加载
    if (self.currentPageIndex == 1) {
        [self.dealsArray removeAllObjects];
    }
    
//    把数据转模型存入可变数组中
    [self.dealsArray addObjectsFromArray:[ZMDealModel objectArrayWithKeyValuesArray:result[@"deals"]]];
    
//    获取当前条件下的数据总数
    self.totalCount = [result[@"total_court"] integerValue];
    
//    重新加载数据
    [self.collectionView reloadData];
    
//    停止刷新
    [self.collectionView.header endRefreshing];
    [self.collectionView.footer endRefreshing];
}

#pragma mark 请求失败后的代理方法
- (void)request:(DPRequest *)request didFailWithError:(NSError *)error {
    
//    停止刷新
    [self.collectionView.header endRefreshing];
    [self.collectionView.footer endRefreshing];
    
//    提示用户
    [MBProgressHUD showError:@"服务器傻了" toView:self.view];
    
//    如果当前页面请求数据失败，将页面书减一，下次重新加载，避免丢数据
    if (self.currentPageIndex > 1) {
        self.currentPageIndex--;
    }
}

#pragma mark 设置状态栏左边按钮
- (void)setupLeftNav {

    //创建logo
    UIBarButtonItem *logoItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_meituan_logo"] style:UIBarButtonItemStylePlain target:self action:nil];
//    不可与用户交互
    logoItem.enabled = NO;
    
    
//    分类按钮
    ZMNavTopView *categoryTopView = [ZMNavTopView navTopView];
    
    [categoryTopView addTarget:self action:@selector(categoryButtonClick)];
    
    [categoryTopView setTitle:@"全部分类"];
    [categoryTopView setSubTitle:@""];
    
    [categoryTopView setIconWithName:@"icon_category_-1" withHighlightIconName:@"icon_category_highlighted_-1"];
    
    UIBarButtonItem *categoryItem = [[UIBarButtonItem alloc] initWithCustomView:categoryTopView];
    self.categoryItem = categoryItem;
    
    
//    区域按钮
    ZMNavTopView *districtTopView = [ZMNavTopView navTopView];
    [districtTopView addTarget:self action:@selector(districtButtonClick)];
    
    [districtTopView setTitle:@"北京-全部"];
    [districtTopView setSubTitle:@""];
    
    UIBarButtonItem *districtItem = [[UIBarButtonItem alloc] initWithCustomView:districtTopView];
    self.districtItem = districtItem;
    
    
//    排序按钮
    ZMNavTopView *sortTopView = [ZMNavTopView navTopView];
    [sortTopView addTarget:self action:@selector(sortButtonClick)];
    
    [sortTopView setTitle:@"排序"];
    [sortTopView setSubTitle:@"默认排序"];
    [sortTopView setIconWithName:@"icon_sort" withHighlightIconName:@"icon_sort_highlighted"];
    
    UIBarButtonItem *sortItem = [[UIBarButtonItem alloc] initWithCustomView:sortTopView];
    
    self.navigationItem.leftBarButtonItems = @[logoItem,categoryItem,districtItem,sortItem];
    
    self.sortItem = sortItem;
}

#pragma mark 分类按钮点击
-(void)categoryButtonClick {
//创建内容视图
    ZMCategoryViewController *categoryVC = [[ZMCategoryViewController alloc] init];
    
//    创建popover控制器
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:categoryVC];
    
    [popover presentPopoverFromBarButtonItem:self.categoryItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    
}

#pragma mark 区域按钮点击
-(void)districtButtonClick {

    ZMdistrictViewController *districtVC = [[ZMdistrictViewController alloc] init];
    
    //    获取数据，，通过通知得到的城市名，去便利cities
    NSArray *citise = [ZMCitysModel objectArrayWithFilename:@"cities.plist"];
    
    for (ZMCitysModel *cityModel in citise) {
        
        if ([cityModel.name isEqualToString:self.selectCityName]) {
            
            districtVC.districtArray = cityModel.districts;
        }
    }
    
    
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:districtVC];
    
    [popover presentPopoverFromBarButtonItem:self.districtItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

#pragma mark 排序按钮点击
-(void)sortButtonClick {
    
    //创建内容视图
    ZMSortViewController *sortVC = [ZMSortViewController new];
    
    //    创建popover控制器
    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:sortVC];
    
    [popover presentPopoverFromBarButtonItem:self.sortItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    


    
}
#pragma mark 设置状态栏右边按钮
-(void)setupRightNav {

//    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    
//    [searchBtn setImage:[UIImage imageNamed:@"icon_search"] forState:UIControlStateNormal];
//    [searchBtn setImage:[UIImage imageNamed:@"icon_search_highlighted"] forState:UIControlStateHighlighted];
//    [searchBtn sizeToFit];
//    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
    
    //搜索
    UIBarButtonItem *searchItem = [UIBarButtonItem barButtonItemWithImageName:@"icon_search" hightlightImageName:@"icon_search_highlighted" target:self action:@selector(searchItemClick)];
    //获取自定义视图，然后设置View的宽度
    searchItem.customView.width = 60;
    //地图
    UIBarButtonItem *mapItem = [UIBarButtonItem barButtonItemWithImageName:@"icon_district" hightlightImageName:@"icon_district_highlighted" target:self action:@selector(mapItemClik)];
    //获取自定义视图，然后设置View的宽度
    mapItem.customView.width = 60;
    
    self.navigationItem.rightBarButtonItems = @[mapItem,searchItem];
}
#pragma mark 点击了搜索按钮
-(void)searchItemClick {

}
#pragma mark 点击了地图按钮
-(void)mapItemClik {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>数据源方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
//    如果当前获取数据与总数据相等，隐藏下拉更多
    self.collectionView.footer.hidden = self.dealsArray.count == self.totalCount ? YES : NO;
    
    self.noDataImage.hidden = self.dealsArray.count != 0;
    
     return self.dealsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZMDealCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    // Configure the cell
    cell.dealModel = self.dealsArray[indexPath.item];
    
    return cell;
}

#pragma mark <UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
}

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
